package com.neusoft.elmboot.mapper;

import java.util.List;

import com.neusoft.elmboot.po.OrderDetailet;
//import lombok.Data;
import org.apache.ibatis.annotations.*;

import com.neusoft.elmboot.po.Orders;

@Mapper
public interface OrdersMapper {

	@Insert("INSERT INTO orders(userId,businessId,orderDate,orderTotal,daId,orderState,couponId,discountAmount,couponDiscountAmount,levelDiscountAmount,finalTotal) " +
			"VALUES(#{userId},#{businessId},#{orderDate},#{orderTotal},#{daId},0,#{couponId},#{discountAmount},#{couponDiscountAmount},#{levelDiscountAmount},#{finalTotal})")
	@Options(useGeneratedKeys = true, keyProperty = "orderId", keyColumn = "orderId")
    int saveOrders(Orders orders);

	@Select("select * from orders where orderId=#{orderId}")
	Orders getOrdersById(Integer orderId);

	@Select("select * from orders where userId=#{userId} order by orderId")
	List<Orders> listOrdersByUserId(String userId);

	@Update("update orders set orderState = #{state} where orderId = #{orderId}")
	void updateOrderState(Integer state, Integer orderId);

	@Update("update orders set orderState = #{state}, paymentType = #{paymentType} where orderId = #{orderId}")
	void updateOrderStateAndPaymentType(@Param("state") Integer state,
	                                  @Param("paymentType") String paymentType,
	                                  @Param("orderId") Integer orderId);

	@Update("update orders set refundStatus = #{refundStatus}, refundReason = #{refundReason} where orderId = #{orderId}")
	void updateRefundInfo(@Param("orderId") Integer orderId,
	                    @Param("refundStatus") Integer refundStatus,
	                    @Param("refundReason") String refundReason);

	@Select("select * from orders where businessId = #{businessId}")
    List<Orders> listOrdersByBusinessId(String businessId);

	@Select("select * from orderdetailet where orderId = #{orderId}")
	List<OrderDetailet> getOrderDetailetByOrderId(Integer orderId);

	@Delete("delete from orders where orderId = #{orderId}")
    void delOrderById(Integer orderId);

	@Select("select orderId from orders where userId = #{userId} and businessId = #{businessId} and orderDate = #{orderDate}")
    Integer getOrderId(String userId, String businessId, String orderDate);

	// 获取商家今日订单统计（使用实际支付金额 finalTotal 统计收入）
	@Select("SELECT COUNT(*) as orderCount, COALESCE(SUM(finalTotal), 0) as totalRevenue " +
			"FROM orders " +
			"WHERE businessId = #{businessId} " +
			"AND DATE(orderDate) = CURDATE() " +
			"AND orderState >= 1")
	java.util.Map<String, Object> getTodayOrderStats(String businessId);

	// 获取商家月度订单统计（使用实际支付金额 finalTotal 统计收入与客单价）
	@Select("SELECT COUNT(*) as orderCount, COALESCE(SUM(finalTotal), 0) as totalRevenue, " +
			"COALESCE(AVG(finalTotal), 0) as avgOrderValue " +
			"FROM orders " +
			"WHERE businessId = #{businessId} " +
			"AND YEAR(orderDate) = YEAR(CURDATE()) " +
			"AND MONTH(orderDate) = MONTH(CURDATE()) " +
			"AND orderState >= 1")
	java.util.Map<String, Object> getMonthlyOrderStats(String businessId);

	// ==================== 管理员功能 ====================

	/**
	 * 获取订单总数
	 */
	@Select("SELECT COUNT(*) FROM orders")
	int getOrderCount();

	/**
	 * 获取今日订单数
	 */
	@Select("SELECT COUNT(*) FROM orders WHERE DATE(orderDate) = CURDATE()")
	int getTodayOrderCount();

	/**
	 * 获取本月订单数
	 */
	@Select("SELECT COUNT(*) FROM orders WHERE YEAR(orderDate) = YEAR(CURDATE()) AND MONTH(orderDate) = MONTH(CURDATE())")
	int getMonthlyOrderCount();

	/**
	 * 获取总收入（按实际支付金额 finalTotal 统计）
	 */
	@Select("SELECT COALESCE(SUM(finalTotal), 0) FROM orders WHERE orderState >= 1")
	java.math.BigDecimal getTotalRevenue();

	/**
	 * 获取今日收入（按实际支付金额 finalTotal 统计）
	 */
	@Select("SELECT COALESCE(SUM(finalTotal), 0) FROM orders WHERE DATE(orderDate) = CURDATE() AND orderState >= 1")
	java.math.BigDecimal getTodayRevenue();

	/**
	 * 获取本月收入（按实际支付金额 finalTotal 统计）
	 */
	@Select("SELECT COALESCE(SUM(finalTotal), 0) FROM orders WHERE YEAR(orderDate) = YEAR(CURDATE()) AND MONTH(orderDate) = MONTH(CURDATE()) AND orderState >= 1")
	java.math.BigDecimal getMonthlyRevenue();

	/**
	 * 分页获取订单列表
	 */
	@Select("SELECT o.orderId, o.userId, o.businessId, o.orderDate, o.orderTotal, o.orderState, " +
			"u.userName, b.businessName " +
			"FROM orders o " +
			"LEFT JOIN user u ON o.userId = u.userId " +
			"LEFT JOIN business b ON o.businessId = b.businessId " +
			"ORDER BY o.orderDate DESC LIMIT #{size} OFFSET #{offset}")
	java.util.List<java.util.Map<String, Object>> getOrdersByPage(@org.apache.ibatis.annotations.Param("size") Integer size,
	                                                              @org.apache.ibatis.annotations.Param("offset") Integer offset);
}
